<?php
/**
 * Created by PhpStorm.
 * User: jochen
 * Date: 2017/1/6
 * Time: 下午6:06
 */

namespace EWeiLink\JuPai\Services;


use EWeiLink\JuPai\Contact;
use EWeiLink\JuPai\JpCustomer;
use EWeiLink\JuPai\Planner;
use EWeiLink\JuPai\User;

/**
 * Class RelationService
 * @package EWeiLink\JuPai\Services
 *
 * 用来处理各个模型之间的关系
 */
class RelationService
{
    /**
     * 通过当前登录的用户来查找对应的理财师
     * @param User|\App\Model\User $user
     * @return Planner|null
     */
    public function findPlannerByUser($user)
    {
        return Planner::find($user->id);
    }

    public function bindContactToJP($customer_id, Contact $contact)
    {
        //如果是解绑,不验证
        if ($customer_id === 0) {
            return $contact->update(['customerId' => 0]);
        }

        //钜派客户是否存在,并且属于登录用户
        $jpCustomer = JpCustomer::where([
            'customerId' => $customer_id,
            'plannerId' => $contact->plannerId,
        ])->exists();
        if (!$jpCustomer) {
            return -1;
        }
        //客户是否已绑定微信名片
        $checkCustomer = Contact::where('customerId', $customer_id)
            ->where('_id', '!=', $contact->_id)
            ->exists();
        if ($checkCustomer)
            return -1;
        return $contact->update(['customerId' => $customer_id]);
    }

    public function transferRelation($plannerId, $contact)
    {
        //目标理财师检查
        assert(Planner::where('plannerId', $plannerId)->exists(), '目标理财师不存在');

        //联系人合法性检查
        if ($contact->customerId)
            return false;

        return $contact->update(['plannerId' => $plannerId]);
    }
}